package snaptest.core;

import java.io.IOException;

import snaptest.io.FileIO;

public class ReferenceFileLocator {

	private static final String TMP_FILE_ROOT = "snap-test-tmp";

	private static final String REF_FILE_ROOT = "snap-test-ref";

	private final String filePath;

	private final String fileName;
	
	private final FileIO fileIO;

	public ReferenceFileLocator(Class<?> testClass, String testName) {
		this(testClass, testName, new FileIO());
	}
	
	ReferenceFileLocator(Class<?> testClass, String testName, FileIO fileIO) {
		this.filePath = formatFilePath(testClass);
		this.fileName = formatFileName(testName);
		this.fileIO = fileIO;
	}

	String formatFilePath(Class<?> testClass) {
		return testClass.getPackage().getName().replace('.', '/') + "/" //
				+ testClass.getSimpleName();
	}

	String formatFileName(String testName) {
		return testName + ".txt";
	}

	String getRefFilePath() {
		return REF_FILE_ROOT + "/" + filePath;
	}
	
	String getTmpFilePath() {
		return TMP_FILE_ROOT + "/" + filePath;
	}

	String getFileName() {
		return fileName;
	}

	String getRefFileFullPath() {
		return getRefFilePath() + "/" + getFileName();
	}
	
	String getTmpFileFullPath() {
		return getTmpFilePath() + "/" + getFileName();
	}

	public boolean referenceExist() {
		return fileIO.fileExistOnClassPath(getRefFileFullPath());
	}

	public String loadReference() throws IOException {
		return fileIO.load(getRefFileFullPath());
	}

	public void saveActual(String content) throws IOException {
		fileIO.createFile(getTmpFilePath(), getFileName());
		fileIO.save(getTmpFileFullPath(), content);
	}

}
